import path from 'path'
import fs from 'fs'

// console.log(require.main.filename)
const PROJECT_FILE = '__PROJECT__.json'

const loop = (dir, root) => {
  try {
    // console.log(dir)
    const projectFile = path.resolve(dir, PROJECT_FILE)
    return JSON.parse(fs.readFileSync(projectFile))
  } catch (e) {
    if (dir === root) {
      throw new Error(`CAN NOT find ${PROJECT_FILE} from ${entry} to ${root}`)
    }
    return loop(path.dirname(dir), root)
  }
}

const getProject = () => {
  // console.log(require.main)
  const filename = process.mainModule ? process.mainModule.filename : require.main.filename
  const entry = path.dirname(filename)
  const root = process.cwd()
  return loop(entry, root)
}

// console.log('----------', require.main, process.env.MODE_WORKER)
const PROJECT = process.env.MODE_WORKER === 'yes' ? JSON.parse(process.env.PROJECT) : getProject()

export default PROJECT
